import React, {useEffect, useState} from "react";
import {Button, Divider, message, Pagination, Select, Space, Table} from "antd";
import {CustomButton} from "@/components";
import {ColumnsType} from "antd/es/table";
import {httpDelete, httpGet, httpPost, PageResult, Result} from "@/utils/http";
import {DeleteOutlined, DownloadOutlined, EditOutlined} from "@ant-design/icons";
import {SoftwareAdd, SoftwareUpdate} from "@/pages/software/components";
import {SelectProps} from "rc-select/lib/Select";
import {useSelector} from "@/redux/hooks";
import {useDispatch} from "react-redux";
import {downloadSoftwareActionCreator} from "@/redux/software/action";

export interface SoftwareProp {
	id: number;
	type_name: string;
	title: string;
	version: string;
	os: string;
	url: string;
}

interface SoftPageProp {
	page: number;
	size: number;
	type?: string;
}

interface ModelUpdateProp {
	visible: boolean;
	data?: SoftwareProp
}

interface SelectProp {value: string, label: string}


export const SoftwareStore = () => {



	const columns: ColumnsType<SoftwareProp> = [
		{
			title: '序号',
			key: 'index',
			dataIndex: 'index',
			align: 'center',
			width: 100,
			render: (text, record, index) => <span>{index + 1}</span>,
		},
		{
			title: '类型',
			key: 'type_name',
			dataIndex: 'type_name',
			align: 'center',
		},
		{
			title: '软件',
			key: 'title',
			dataIndex: 'title',
			align: 'center',
		},
		{
			title: '版本',
			key: 'version',
			dataIndex: 'version',
			align: 'center',
		},
		{
			title: '平台',
			key: 'os',
			dataIndex: 'os',
			align: 'center',
		},
		{
			title: '操作',
			key: 'active',
			align: 'center',
			width: 150,
			render: (text, record, index) => (
				<Space size={'small'}>
					<Button size="small" type="link" loading={record.id === software.id && !software.is_result} icon={<DownloadOutlined />} onClick={() => downloadSoftware(record.id)} />
					<Button size="small" type="link" icon={<EditOutlined />} onClick={() => setModelUpdateProp({visible: true, data: record})} />
					<Button size="small" type="link" danger icon={<DeleteOutlined />} onClick={() => deleteBatchSoftware(record.id.toString())}/>
				</Space>
			),
		},
	]


	const dispatch = useDispatch();
	const software = useSelector((state) => state.software);
	const [modelAddProp, setModelAddProp] = useState<boolean>(false)
	const [modelUpdateProp, setModelUpdateProp] = useState<ModelUpdateProp>({visible: false})
	const [pageProp, setPageProp] = useState<SoftPageProp>({page: 1, size: 10});
	const [datasource, setDatasource] = useState<SoftwareProp[]>([]);
	const [total, setTotal] = useState<number>(0);
	const [loading, setLoading] = useState<boolean>(false);
	const [types, setTypes] = useState<SelectProp[]>([]);

	const deleteBatchSoftware = (ids: string) => {
		setLoading(true);
		httpDelete<Result<string>, {ids: string}>('/software/delete', {ids: ids}).then(res => {
			if (res.code === 100200) {
				message.success(res.result);
				loadData();
			} else {
				message.error(res.result);
			}
		}).finally(() => setLoading(false))
	}

	const loadData = () => {
		setLoading(true);
		httpPost<PageResult<SoftwareProp>, SoftPageProp>('/software/page', pageProp).then(res => {
			setLoading(false);
			if (res.code === 100200) {
				const {total, records, page, size} = res.result;
				setTotal(total);
				setDatasource(records);
				setPageProp({...pageProp, page: page, size: size});
			} else {
				message.error(res.message)
			}
		})
	}

	const loadTypes = () => {
		httpGet<Result<string[]>, any>('/software/types').then(res => {
			if (res.code === 100200) {
				let temp: SelectProp[] = [];
				res.result.forEach(item => temp.push({value: item, label: item}))
				setTypes([{ value: 'All', label: '全部' }, ...temp]);
			} else {
				message.error(res.message)
			}
		})
	}

	const downloadSoftware = (id: number) => {
		httpGet<Result<string>, {id: number}>('/software/download', {id: id}).then(res => {
			if (res.code === 100200) {
				dispatch(downloadSoftwareActionCreator({id: id, is_result: false}))
				message.success(res.result);
			} else {
				message.error(res.result);
			}
		})
	}

	const pageChange = (page: number, pageSize: number) => {
	}

	const closeModel = (isLoad: boolean, type: 'add' | 'update') => {
		if (type === 'add') {
			setModelAddProp(false)
		}
		if (type === 'update') {
			setModelUpdateProp({visible: false, data: undefined})
		}
		if (isLoad) {
			loadData()
		}
	}

	const osChange = (value: string) => {}


	useEffect(() => {
		loadTypes();
		loadData();
	}, [])

	return <>
		<Space>
			<Button type="primary" onClick={() => setModelAddProp(true)}>增加</Button>
			<Button type="primary">刷新</Button>
			{/*<CustomButton type="primary" custom="Green" title="刷新"/>*/}
			<Button type="primary" danger disabled>删除</Button>
			<Divider type="vertical"/>
			类型：
			<Select
				defaultValue="All"
				onChange={osChange}
				style={{ width: 100 }}
				options={types}
			/>
			<Divider type="vertical"/>
			平台：
			<Select
				defaultValue="All"
				onChange={osChange}
				style={{ width: 100 }}
				options={[
					{ value: 'All', label: '全部' },
					{ value: 'Linux', label: 'Linux' },
					{ value: 'Mac', label: 'Mac' },
					{ value: 'Win', label: 'Win' }
				]}
			/>
		</Space>
		<Table
			size={'small'}
			style={{ marginTop: 10 }}
			columns={columns}
			dataSource={datasource}
			bordered
			pagination={false}
			loading={loading}
		/>
		<Pagination
			size="default"
			total={total}
			style={{ textAlign: 'right'}}
			onChange={(page, pageSize) => pageChange(page, pageSize)}
		/>
		<SoftwareAdd visible={modelAddProp} onCancel={(isLoad) => closeModel(isLoad, 'add')} />
		<SoftwareUpdate visible={modelUpdateProp.visible} currData={modelUpdateProp.data!} onCancel={(isLoad) => closeModel(isLoad, 'update')} />
	</>
}
